package zj.it.bhne.greendao;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

import zj.it.bhne.greendao.entity.Teachers;

import static zj.it.bhne.greendao.MyApplication.getToast;
import static zj.it.bhne.greendao.MyApplication.mContext;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private zj.it.bhne.greendao.TeachersDao teachersDao;
    private ListView listView;
    private String TAG = "MainActivity";
    private MainAdapter mainAdapter;

    @Override
    protected void onResume() {
        super.onResume();
        teachersList = teachersDao.queryBuilder().list();
        mainAdapter = new MainAdapter(getApplicationContext(),teachersList);
        listView.setAdapter(mainAdapter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initData();
        initView();
    }

    private void initData() {
        teachersDao = MyApplication.getInstances().getDaoSession().getTeachersDao();
    }

    private void initView() {
        Button create = findViewById(R.id.create);
        create.setOnClickListener(this);
        listView = findViewById(R.id.listView);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Teachers teachers = (Teachers) mainAdapter.getItem(position);
                Intent intent = new Intent(mContext(),Main2Activity.class);
                intent.putExtra("tid",teachers.getId());
                startActivity(intent);
                Log.e(TAG, "onItemClick: "+teachers.getId());
            }
        });
    }

    List<Teachers> teachersList = new ArrayList<>();

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.create:
                Teachers teachers = new Teachers(null, "朱江", 22);
                long num = teachersDao.insert(teachers);
                if (num > 0) {
                    getToast(mContext(),"添加成功");
                    teachersList = teachersDao.queryBuilder().list();
                    mainAdapter = new MainAdapter(getApplicationContext(),teachersList);
                    listView.setAdapter(mainAdapter);
                }
                break;
        }
    }
}
